﻿using System;

#if WINDOWS_PHONE_APP
using Windows.Phone.UI.Input;
#endif
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;

namespace PrismAdapter
{
    /// <summary>
    /// Phone support extension methods.
    /// </summary>
    public static class PagePhoneSupportExtensions
    {
        /// <summary>
        /// add platform support.
        /// </summary>
        /// <param name="self"></param>
        public static void EnablePlatformSupport(this PrismNavigationHelper self)
        {
#if WINDOWS_PHONE_APP
            EnableHardwareBackButton(self);
            EnableLanguageSetting();
#endif
        }

        /// <summary>
        /// add hardware back button support.
        /// </summary>
        /// <param name="self">prism adapter's NavigationHelper</param>
        [Obsolete("use EnablePlatformSupport method")]
        public static void EnablePhoneSupport(this PrismNavigationHelper self)
        {
#if WINDOWS_PHONE_APP
            EnablePlatformSupport(self);
#endif
        }

#if WINDOWS_PHONE_APP

        private static void EnableHardwareBackButton(PrismNavigationHelper self)
        {
            // hard back button
            EventHandler<BackPressedEventArgs> back = (s, e) =>
            {
                if (self.CanGoBack())
                {
                    e.Handled = true;
                    self.GoBack();
                }
            };

            RoutedEventHandler loaded = (s, e) =>
            {
                HardwareButtons.BackPressed += back;
            };

            RoutedEventHandler unloaded = null;
            unloaded = (s, e) =>
            {
                self.Page.Loaded -= loaded;
                self.Page.Unloaded -= unloaded;
                HardwareButtons.BackPressed -= back;
            };

            self.Page.Loaded += loaded;
            self.Page.Unloaded += unloaded;
        }

        private static void EnableLanguageSetting()
        {
            PrismAdapterBootstrapper.Current.RootFrame.Language = System.Globalization.CultureInfo.CurrentUICulture.Name;
        }
#endif
    }
}
